//显示提示消息
var global = {
	isMobile : function() {
		var browser = {
			versions : function() {
				var u = navigator.userAgent;
				return {
					trident : u.indexOf('Trident') > -1, // IE内核
					presto : u.indexOf('Presto') > -1, // opera内核
					webKit : u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
					gecko : u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, // 火狐内核
					mobile : !!u.match(/AppleWebKit.*Mobile.*/)
							|| !!u.match(/AppleWebKit/), // 是否为移动终端
					ios : !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
					android : u.indexOf('Android') > -1
							|| u.indexOf('Linux') > -1, // android终端或者uc浏览器
					iPhone : u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, // 是否为iPhone或者QQHD浏览器
					iPad : u.indexOf('iPad') > -1, // 是否iPad
					webApp : u.indexOf('Safari') == -1
				// 是否web应该程序，没有头部与底部
				};
			}()
		};
		if (browser.versions.android) {
			return true;
		} else if (browser.versions.iPhone || browser.versions.iPad) {
			return true;
		} else {
			return false;
		}
	},
	isIpad : function() {
		var browser = {
				versions : function() {
					var u = navigator.userAgent;
					return {
						trident : u.indexOf('Trident') > -1, // IE内核
						presto : u.indexOf('Presto') > -1, // opera内核
						webKit : u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
						gecko : u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, // 火狐内核
						mobile : !!u.match(/AppleWebKit.*Mobile.*/)
							|| !!u.match(/AppleWebKit/), // 是否为移动终端
						ios : !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
						android : u.indexOf('Android') > -1
							|| u.indexOf('Linux') > -1, // android终端或者uc浏览器
						iPhone : u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, // 是否为iPhone或者QQHD浏览器
						iPad : u.indexOf('iPad') > -1, // 是否iPad
						webApp : u.indexOf('Safari') == -1
						// 是否web应该程序，没有头部与底部
					};
				}()
		};
		if (browser.versions.iPhone || browser.versions.iPad) {
			return true;
		} else {
			return false;
		}
	},
	displayAsImage : function(obj, showPhotoId) {
		var file = obj.files[0];
		var urlObject = webkitURL || URL;
		var imgURL = urlObject.createObjectURL(file), img = document
				.querySelector("#" + showPhotoId);
		img.onload = function() {
			urlObject.revokeObjectURL(imgURL);
		};
		img.src = imgURL;
	},
	alert : function(mess, submit, cancle) {
		$('#dialog-alert h4').html(mess);
		$('#dialog-alert').popup('open');
	},
	confirm : function(mess, submit, cancle) {
		$('#dialog-confirm h3.ui-title').html(mess);
		$('#dialog-confirm button').unbind().bind("click", function() {
			submit();
			$('#dialog-confirm').popup('close');
		});
		if (cancle) {
			$('#dialog-confirm a').unbind().bind("click", function() {
				cancle();
			});
		}
		$('#dialog-confirm').popup('open');

	},
	uploadDialog : function(mess, okFun, templeFun) {
		$('#dialog-upload-header').html(mess);
		$('#dialog-upload-submit').unbind().bind("click", function() {
			okFun();
			$('#dialog-upload').popup('close');
		});
		$('#dialog-upload-temple').unbind().bind("click", function() {
			templeFun();
			$('#dialog-upload').popup('close');
		});
		$('#dialog-upload').popup('open');
	},

	selectDialog : function(url, title, target, typeId) {
		var func = function(obj) {
			var item = $(obj);
			$("#" + target + "Id").val(item.attr("id"));
			$("#" + target + "Name").val(item.html());
		}
		if (typeId) {
			url += "?type=" + $("#" + typeId).val();
		}
		global.singleSelectDialog(url, title, "", func);
	},

	singleSelectDialog : function(url, title, extIds, func) {
		$('#dialog-select h1').html(title);
		$('#dialog-select ol').undelegate().delegate("li", "click", function() {
			$('#dialog-select').popup('close');
			func(this);
		});
		jQuery.ajax({
			type : 'GET',
			url : url,
			success : function(data) {
				var jsonData = $.parseJSON(data);
				var html = "";
				for ( var i = 0, k = jsonData.length; i < k; i++) {
					var node = jsonData[i];
					if (extIds.indexOf(node.id) > -1) {
						continue;
					}
					if (node.mobile) {
						html += '<li id=' + node.id + ' name=' + node.name
								+ ' mobile=' + node.mobile + '>' + node.name + '('
								+ node.mobile + ')</li>';
					} else {
						html += '<li id=' + node.id + ' name=' + node.name + '>' + node.name +'</li>';
					}
				}
				$('#dialog-select ol').html(html);
				$('#dialog-select ol').listview('refresh');
				$('#dialog-select').popup('open');
			},
			error : function(data) {
				showTip("查询失败");
			}
		});
	},

	addMultSelectList : function(url, title, extIds, targetId) {
		var func = function() {
			var html = "";
			var items = $('#dialog-mult-select ul li input');
			for ( var i = 0; i < items.length; i++) {
				var item = $(items[i]);
				if (item.prop("checked") == true) {
					html += '<li id="' + item.attr("id") + '"><a>' + item.val()
							+ '</a><a class="delete"></a></li>';
				}
			}
			$("#" + targetId).append(html);
			$("#" + targetId).listview('refresh');
			$("#" + targetId).trigger("create");
			$("#" + targetId).undelegate().delegate("li .delete", "click",
					function() {
						var item = $(this).parent();
						item.remove();
					});
		};
		global.multSelectDialog(url, title, extIds, func);
	},

	multSelectDialog : function(url, title, extIds, func) {
		$('#dialog-mult-select h1').html(title);
		var checkAll = $('#dialog-mult-select .checkAll');
		checkAll.attr("checked", false);
		checkAll.checkboxradio("refresh");
		$('#dialog-mult-select .ui-filterable input').val("");
		$('#submitBtn').die().live('click', function() {
			$('#dialog-mult-select').popup('close');
			func();
		});
		$('#dialog-mult-select .checkAll').die().live('click', function() {
			var items = $('#dialog-mult-select ul li');
			for ( var i = 0; i < items.length; i++) {
				var item = $(items[i]);
				if(item.attr("class").indexOf("ui-screen-hidden") == -1) {
					var child = item.find("input");
					child.attr("checked", this.checked);
					child.checkboxradio("refresh");
				}
			}
		});
		jQuery.ajax({
			type : 'GET',
			url : url,
			success : function(data) {
				var jsonData = $.parseJSON(data);
				var html = "";
				for ( var i = 0, k = jsonData.length; i < k; i++) {
					var node = jsonData[i];
					if (extIds.indexOf(node.id) > -1) {
						continue;
					}
					html += '<li><input type="checkbox" name="' + node.id
							+ '" id="' + node.id + '" value="' + node.name
							+ '">';
					if (node.mobile) {
						html += '<label for="' + node.id + '">' + node.name
								+ '(' + node.mobile + ')</label></li>';
					} else {
						html += '<label for="' + node.id + '">' + node.name
								+ '</label></li>';
					}
				}
				$('#dialog-mult-select ul').html(html);
				$('#dialog-mult-select ul').listview('refresh');
				$('#dialog-mult-select').trigger("create");
				$('#dialog-mult-select').popup('open');
			},
			error : function(data) {
				showTip("查询失败");
			}
		});
	},
	DBC2SBC : function(str) {
		var result = '';
		for ( var i = 0; i < str.length; i++) {
			code = str.charCodeAt(i);// 获取当前字符的unicode编码
			// 在这个unicode编码范围中的是所有的英文字母已及各种字符
			if (code >= 65281 && code <= 65373) {
				result += String.fromCharCode(str.charCodeAt(i) - 65248);// 把全角字符的unicode编码转换为对应半角字符的unicode码
			} else if (code == 12288) { // 空格
				result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
			} else {
				result += str.charAt(i);
			}
		}
		return result;
	}
};

function beforeUpload() {
	var file = document.getElementById('fileToUpload').files[0];
	if (file) {
		/*
		 * var fileSize = 0; if (file.size > 1024 * 1024) fileSize =
		 * (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() +
		 * 'MB'; else fileSize = (Math.round(file.size * 100 / 1024) /
		 * 100).toString() + 'KB';
		 */
		var types = new Array('application/excel', 'application/vnd.ms-excel', 'application/msexcel','application/kswps','application/ksdps','application/kset');
		if (types.indexOf(file.type) == -1) {
			$("#dialog-upload-errorMsg").html("文件类型不正确，无法上传");
			return false;
		}
		return true;
	} else {
		$("#dialog-upload-errorMsg").html("未选择文件，无法上传");
		return false;
	}
}
function confirmx(mess, href) {
	var fun = function() {
		window.location.href = href;
	};
	global.confirm(mess, fun);
	return false;
}
// 显示加载框
function loading(mess) {
	showTip(mess);
}
function showTip(mess) {
	new Toast({
		context : $('body'),
		message : mess,
		bottom : "100px"
	}).show();
	// $('#dialog-tip').popup('open');
	// $('#dialog-tip p').html(mess);
}
// 短信发送
function sendMessage(form, target, immediateSend) {
	//暂时屏蔽手动发送短信的功能
	global.alert("此功能即将开放，敬请期待！");
	return;
	if (target == 'sms') {
		var now = new Date();
		var hour = now.getHours();
		if (immediateSend == 'true') {
			loading('正在发送，请稍等...');
			form.submit();
			return true;
		}
		if (hour > 17 || hour < 14) {
			global.confirm('现在不是短信发送的时间段，是否保存短信？', form.submit());
		} else {
			loading('正在提交，请稍等...');
			form.submit();
		}
	} else {
		loading('正在提交，请稍等...');
		form.submit();
	}
}
// 是否弹出任务密码dialog
function loginPasswordPopup(func) {
	global.loginPasswordFunc = func;
	if (global.loginPassword !== "") {
		$("#dialog-loginCheck input").val("");
		$('#dialog-loginCheck label').html("");
		$('#dialog-loginCheck').popup('open');
		$('#dialog-loginCheck input').focus();
	} else {
		if (typeof (func) == "string") {
			window.location.href = global.loginPasswordFunc;
		} else {
			func();
		}
	}
}
// 任务密码效验
function loginPasswordCheck() {
	var input = $("#dialog-loginCheck input").val();
	input = global.DBC2SBC(input);
	if (input == '') {
		var label = $('#dialog-loginCheck label');
		label.html("未输入任务密码");
		label.css("display", 'block');
		return false;
	}
	if (input != global.loginPassword) {
		var label = $('#dialog-loginCheck label');
		label.html("任务密码不正确");
		label.css("display", 'block');
		return false;
	}
	$('#dialog-loginCheck').popup('close');
	if (typeof (global.loginPasswordFunc) == "string") {
		window.location.href = global.loginPasswordFunc;
	} else {
		global.loginPasswordFunc();
	}
	return true;
};

// 是否弹出管理密码dialog
function bossPasswordPopup(func) {
	global.bossPasswordFunc = func;
	if (global.bossPassword !== "") {
		$("#dialog-bossCheck input").val("");
		$('#dialog-bossCheck label').html();
		$('#dialog-bossCheck').popup('open');
		$('#dialog-bossCheck input').focus();
	} else {
		if (typeof (func) == "string") {
			window.location.href = global.bossPasswordFunc;
		} else {
			func();
		}
	}
}
//
function bossLoginDeletePopup(info, href) {
	var func = function() {
		var fun = function() {
			window.location.href = href;
		};
		global.confirm(info, fun);
	}
	bossPasswordPopup(func);
}
//
function bossLoginSubmit(bossPassword, form, target, immediateSend) {
	var func = function() {
		sendMessage(form, target, immediateSend);
	}
	bossPasswordPopup(func);
}
// 管理密码效验
function bossPasswordCheck() {
	var input = $("#dialog-bossCheck input").val();
	input = global.DBC2SBC(input);
	if (input == '') {
		var label = $('#dialog-bossCheck label');
		label.html("未输入管理密码");
		label.css("display", 'block');
		return false;
	}
	if (input !== global.bossPassword) {
		var label = $('#dialog-bossCheck label');
		label.html("管理密码不正确");
		label.css("display", 'block');
		return false;
	}
	$('#dialog-bossCheck').popup('close');
	if (typeof (global.bossPasswordFunc) == "string") {
		window.location.href = global.bossPasswordFunc;
	} else {
		global.bossPasswordFunc();
	}
};
function loadingSortTable(id) {
	$("#" + id).dataTable({
		"sPaginationType" : "full_numbers",
		"bStateSave" : true,
		"bPaginate" : false,
		"bLengthChange" : false,
		"bFilter" : false,
		"bSort" : true,
		"bInfo" : false,
		"oLanguage" : {
			"sLengthMenu" : "每页显示 _MENU_ 条记录",
			"sZeroRecords" : "抱歉， 没有找到",
			"sInfo" : "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
			"sInfoEmpty" : "没有数据",
			"sInfoFiltered" : "(从 _MAX_ 条数据中检索)",
			"sZeroRecords" : "没有检索到数据",
			"sSearch" : "搜索:",
			"oPaginate" : {
				"sFirst" : "首页",
				"sPrevious" : "前一页",
				"sNext" : "后一页",
				"sLast" : "尾页"
			}
		}
	});
}
function loadingDisplayTable(id) {
	$("#" + id).dataTable({
		"sPaginationType" : "full_numbers",
		"bPaginate" : false,
		"bLengthChange" : false,
		"bFilter" : false,
		"bSort" : false,
		"bInfo" : false,
		"bAutoWidth" : false,
		"oLanguage" : {
			"sLengthMenu" : "每页显示 _MENU_ 条记录",
			"sZeroRecords" : "抱歉， 没有找到",
			"sInfo" : "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
			"sInfoEmpty" : "没有数据",
			"sInfoFiltered" : "(从 _MAX_ 条数据中检索)",
			"sZeroRecords" : "没有检索到数据",
			"sSearch" : "搜索:",
			"oPaginate" : {
				"sFirst" : "首页",
				"sPrevious" : "前一页",
				"sNext" : "后一页",
				"sLast" : "尾页"
			}
		}
	});
}

// 管理密码效验
function directOpenURL(url) {
	window.location.href = url;
}
//
function cacheEmployees() {
	jQuery.ajax({
		url : "${ctx}/employee/employee/employeeData",
		type : "post",
		data : {},
		success : function(data) {
			sessionStorage.employees = data;
		},
		error : function(data) {
			showTip("获取员工列表失败");
		}
	});
}
// 填充服务专员
function loadingEmpoyees(selectObj, employeeID) {
	var values = eval(sessionStorage.employees);
	var id = "div#" + selectObj.id + "-button span";
	for ( var int = 0; int < values.length; int++) {
		var varItem = new Option(values[int].name, values[int].id);
		if (values[int].id == employeeID) {
			$(id).text(values[int].name);
		}
		selectObj.options.add(varItem);
	}
	if (employeeID == '' && values[0].name != '') {
		$(id).text(values[0].name);
	}
}

function deleteTarget(message, deleteURL) {
	global.confirm(message, function() {
		window.location.href = deleteURL;
	});// confirm
}
// 查询与员工相关的客户
function findCustomerByEmployee(ctx, eid) {
	if (!eid) {
		return;
	}
	var url = ctx + "/sms/sendStoreGroupToCustomer/findCustomers?employeeId="
			+ eid;
	jQuery.ajax({
		type : 'GET',
		url : url,
		success : function(data) {
			if (data) {
				var dataJson = eval("(" + data + ")");
				$("#customerIds option").remove();
				for ( var i = 0, len = dataJson.length; i < len; i++) {
					var c = dataJson[i];
					var option = "<option value='" + c.id + "' selected>"
							+ c.name + "(" + c.mobile + ")</option>";
					$("#customerIds").append(option);
				}
				$("#customerIds").selectmenu("refresh");
				var sel = "";
				$("#customerIds").find("option").each(function(id, op) {
					if (op.selected) {
						sel += op.text + "<br/>";
					}
				});
				$("#selectCustomer").html(sel);
			}
		}
	});
}
// 与服务器端同步
function syncToServer(url, backFun) {
	jQuery.ajax({
		type : 'GET',
		url : url,
		success : function(data) {
			backFun();
		}
	});
}
function removeChild(parentID, childID) {
	var list = document.getElementById(parentID);
	var item = document.getElementById(childID);
	if (list != null && item != null) {
		list.removeChild(item);
	}
}

var buyProducts = {
	registerSelection : function(dialogID, type) {// registerSelectionListener
		$(dialogID + " ul li").delegate("a", "click", function() {
			var item = $(this);
			$("#type").val(type);
			$("#productID").val(item.attr("id"));
			$("#productName").val(item.attr("name"));
			$("#productSpec").val(item.attr("spec"));
			$("#productRetailPrice").val(item.attr("price"));
			$(dialogID).popup("close");
			$("#contentTable tbody tr").removeClass("select_active");
			$("#editing").val("add");
			$("#currentAmount").val(0);
			$("div#okbutton button").text("确认添加");

			$("#inputForm").valid();
		});
	},
	registerEditSelection : function() {// registerSelectionListener
		$("#contentTable tbody").delegate("tr", "click", function() {
			var item = $(this);
			$("#productID").val(item.attr("id"));
			$("#productName").val(item.attr("name"));
			$("#productSpec").val(item.attr("spec"));
			$("#productRetailPrice").val(item.attr("price"));
			$("#count").val(item.attr("amount"));
			$("#editing").val("update");
			$("#currentAmount").val(item.attr("amount"));
			$("div#okbutton button").text("保存更改");

			$("#contentTable tbody tr").removeClass("select_active");
			item.addClass("select_active");
		});
	},
	deleteTr : function(message, productID, type) {
		var fun = function() {
			jQuery.ajax({
				// start ajax
				url : "clientDeleteProduct",
				type : "post",
				data : {
					"productID" : function() {
						return productID;
					},
					"type" : type,
				},
				success : function(data) {
					showTip(data);
					var objs = eval(data);
					if (objs[0].result) {
						showTip("删除成功");
						var dialogID = "";
						if ('system' == type) {
							dialogID = "#selectProduct2";
						} else {
							dialogID = "#selectProduct";
						}
						buyProducts.removeItem(dialogID, productID);
						if (productID == $("#productID").val()) {
							cashPro.clear();
						}
					} else {
						showTip(objs[0].message);
					}
				},
				error : function(data) {
					showTip("删除失败");
				}
			// end ajax
			});
		};// fun
		global.confirm(message, fun);// confirm
	},
	removeItem : function(dialogID, productID) {
		removeChild("tbody", productID);
		$(dialogID + " ul a#" + productID).show();
		$("#contentTable").trigger("create");
	},

	addItem : function(type) {
		var pName = $("#productName").val();
		var spec = $("#productSpec").val();
		var pid = $("#productID").val();
		var amount = $("#count").val();
		var retailPrice = $("#productRetailPrice").val();
		var line = "<tr id="
				+ pid
				+ " name="
				+ pName
				+ " spec="
				+ spec
				+ " price="
				+ retailPrice
				+ " amount="
				+ amount
				+ ">"
				+ "<td>"
				+ pName
				+ "</td>"
				+ "<td>"
				+ spec
				+ "</td>"
				+ "<td id='amount'>"
				+ amount
				+ "</td>"
				+ "<td>"
				+ retailPrice
				+ "</td>"
				+ "<td>"
				+ "<a data-role='button' data-inline='true' data-icon='delete' data-iconpos='notext' onclick="
				+ "buyProducts.deleteTr('确定删除产品：" + pName + "?'," + pid + ",'" + type
				+ "')>删除</a>" + "</td>" + "</tr>";
		$("#contentTable").append(line);
		$("#contentTable").trigger("create");
		var dialogID = "";
		if ('system' == type) {
			dialogID = "#selectProduct2";
		} else {
			dialogID = "#selectProduct";
		}
		$(dialogID + " ul a#" + pid).hide();
	},
	updateTrAmount : function(trID, amount) {
		$("#contentTable tr#" + trID).attr("amount", amount);
		$("#contentTable tr#" + trID + " td#amount").text(amount);
		$("#contentTable").trigger("create");
	},
	doCommit : function() {
		jQuery.ajax({
			url : "clientAddProduct",
			type : "post",
			data : {
				productID : function() {
					return $("#productID").val();
				},
				employeeID : function() {
					return $("#employeeProductID").val();
				},
				amount : function() {
					return $('#count').val();
				},
				type : $("#type").val(),
				editing : $("#editing").val(),
				currentAmount : $("#currentAmount").val(),
			},
			success : function(data) {
				var objs = eval(data);
				showTip(objs.result);
				if (objs[0].result) {
					if (objs[0].editing == "update") {
						showTip("保存成功");
						buyProducts.updateTrAmount(objs[0].id, objs[0].amount);
					} else {
						showTip("添加成功");
						buyProducts.addItem($("#type").val());
					}
					cashPro.clear();
				} else {
					showTip(objs[0].message);
				}
			},
			error : function(data) {
				showTip("保存失败");
			}
		});// end ajax
	},
	registerSubmitHandler : function(productNameKey) {// validateInputForm
		$("#inputForm").validate({
			submitHandler : function(form) {
				var editing = $("#editing").val();
				var amount = $('#count').val();
				var currentAmount = $("#currentAmount").val();
				if (editing == "update") {
					if (amount == currentAmount) {
						showTip("数量未更新");
						return;
					}
				}
				buyProducts.doCommit();
			},
			focusInvalid : false,
			rules : {
				count : {
					required : true,
					digits : true,
					min : 1,
					max : 10000
				},
				productNameKey : {
					required : true
				}
			},
			errorContainer : "#messageBox",
			errorPlacement : function(error, element) {
				$("#messageBox").text("输入有误，请先更正。");
				if (element.is(":checkbox") || element.is(":radio")) {
					error.appendTo(element.parent().parent());
				} else {
					error.insertAfter(element);
				}
			},
			messages : {}
		});// validate
	},
	loadingProductList : function(dialogID, type) {
		jQuery.ajax({
			url : "clientLoadingProduct",
			type : "post",
			data : {
				"type" : type,
			},
			success : function(data) {
				var objs = eval(data);
				var addedIds = eval(objs[0].addedProducts);
				var html = "";
				for ( var index = 1; index < objs.length; index++) {
					var element = objs[index];
					html += "<li><a name='" + element.name + "' spec='"
							+ element.spec + "'	id='" + element.id
							+ "' price='" + element.retailPrice + "' href='#'>"
							+ element.name + "</a></li>";
				}
				$(dialogID + " ul").append(html);
				$(dialogID + " ul").listview('refresh');
				buyProducts.registerSelection(dialogID, type);
				for (index = 0; index < addedIds.length; index++) {
					element = addedIds[index];
					$(dialogID + " ul" + " a#" + element.id).hide();
				}
			},
			error : function(data) {
				showTip("加载产品列表失败");
			}
		});// end ajax
	},
};

var cashPro = {
	removeItem : function(productID) {
		removeChild("tbody", productID);
		$("#productsList a#" + productID).show();
		$("#contentTable").trigger("create");
	},
	clear : function() {
		$("#productID").val("");
		$("#productName").val("");
		$("#productSpec").val("");
		$("#productRetailPrice").val(0);
		$("#count").val(1);
	},

	dropNomemberShopping : function(ctx) {
		// 自定义按钮
		global.confirm("确定要取消本次消费，取消后，购物车将被清空？",
				function() {
					window.location.href = ctx
							+ "/cash/consume/nonmember/dropShopping";
				});// confirm

	},
	submitShopping : function(inputForm, ctx) {// for non-member
		$(inputForm).validate({
			submitHandler : function(form) {
				jQuery.ajax({
					url : ctx + "/cash/consume/canCommit",
					type : "post",
					data : {},
					success : function(data) {
						if (data == 'false') {
							showTip("请先添加产品，或者护理项目");
							return;
						} else {
							form.submit();
						}

					},
					error : function(data) {
						showTip("获取员工列表失败");
					}
				});

			},
			focusInvalid : false,
			rules : {},
			errorContainer : "#messageBox",
			errorPlacement : function(error, element) {
			},
			messages : {}
		});// validate
	},
	deleteTr : function(message, productID, type) {
		global.confirm(message, function() {
			jQuery.ajax({
				url : "clientDeleteProduct",
				type : "post",
				data : {
					"productID" : function() {
						return productID;
					},
					"type" : type
				},
				success : function(data) {
					showTip(data);
					var objs = eval(data);
					if (objs[0].result) {
						showTip("删除成功");
						cashPro.removeItem(productID);
					} else {
						showTip(objs[0].message);
					}

				},
				error : function(data) {
					showTip("删除失败");
				}

			});// end ajax
		});// confirm
	},
	addItem : function(type) {
		var pName = $("#productName").val();
		var spec = $("#productSpec").val();
		var pid = $("#productID").val();
		var amount = $("#count").val();
		var retailPrice = $("#productRetailPrice").val();
		var line = "<tr id="
				+ pid
				+ ">"
				+ "<td>"
				+ pName
				+ "</td>"
				+ "<td>"
				+ spec
				+ "</td>"
				+ "<td>"
				+ amount
				+ "</td>"
				+ "<td>"
				+ retailPrice
				+ "</td>"
				+ "<td>"
				+ "<a data-role='button' data-inline='true' data-icon='delete' data-iconpos='notext' onclick="
				+ "cashPro.deleteTr('确定删除产品：" + pName + "?'," + pid + ",'"
				+ type + "')>删除</a>" + "</td>" + "</tr>";
		$("#contentTable").append(line);
		$("#contentTable").trigger("create");
		$("#productsList a#" + pid).hide();
	},
	registerSelectionListener : function() {// registerSelectionListener
		$("#selectProductEvent ul li").delegate("a", "click", function() {
			var item = $(this);
			$("#productID").val(item.attr("id"));
			$("#productName").val(item.attr("name"));
			$("#productSpec").val(item.attr("spec"));
			$("#productRetailPrice").val(item.attr("price"));
			$("#selectProduct").popup("close");
			$("#inputForm").valid();
		});
	},
	loadingProductList : function(type) {
		jQuery.ajax({
			url : "clientLoadingProduct",
			type : "post",
			data : {
				"type" : type,
			},
			success : function(data) {
				var objs = eval(data);
				var addedIds = eval(objs[0].addedProducts);
				var html = "";
				for ( var index = 1; index < objs.length; index++) {
					var element = objs[index];
					html += "<li><a name='" + element.name + "' spec='"
							+ element.spec + "'	id='" + element.id
							+ "' price='" + element.retailPrice + "' href='#'>"
							+ element.name + "</a></li>";
				}
				$("#productsList").append(html);
				$("#productsList").listview('refresh');
				cashPro.registerSelectionListener();
				for (index = 0; index < addedIds.length; index++) {
					element = addedIds[index];
					$("#productsList a#" + element.id).hide();
				}
			},
			error : function(data) {
				showTip("加载产品列表失败");
			}
		});// end ajax
	},
	doCommit : function(producttype) {
		jQuery.ajax({
			url : "clientAddProduct",
			type : "post",
			data : {
				productID : function() {
					return $("#productID").val();
				},
				employeeID : function() {
					return $("#employeeProductID").val();
				},
				amount : function() {
					return $('#count').val();
				},
				type : producttype,
			},
			success : function(data) {
				var objs = eval(data);
				showTip(objs.result);
				if (objs[0].result) {
					showTip("添加成功");
					cashPro.addItem(producttype);
					cashPro.clear();
				} else {
					showTip(objs[0].message);
				}
			},
			error : function(data) {
				showTip("保存失败");
			}

		});// end ajax
	},
	validateInputForm : function(producttype, productNameKey) {// validateInputForm
		$("#inputForm").validate({
			submitHandler : function(form) {
				// var product = $('#productName').val();
				// var count = Number($('#count').val());
				// var price = Number($('#productRetailPrice').val());
				// var costMoney = count * price;
				// var content = "您选择了购买产品【" + product + "】" + count
				// + "个, 零售价合计" + costMoney + "元, 请确认消费信息是否正确？";
				// 自定义按钮
				// global.confirm(content,function(){
				// cashPro.doCommit(producttype);
				// });// confirm
				cashPro.doCommit(producttype);
			},
			focusInvalid : false,
			rules : {
				count : {
					required : true,
					digits : true,
					min : 1,
					max : 10000
				},
				productNameKey : {
					required : true
				}
			},
			errorContainer : "#messageBox",
			errorPlacement : function(error, element) {
				$("#messageBox").text("输入有误，请先更正。");
				if (element.is(":checkbox") || element.is(":radio")) {
					error.appendTo(element.parent().parent());
				} else {
					error.insertAfter(element);
				}
			},
			messages : {}
		});// validate
	},

};

function initCustomerDetailReturnButton(ctx, emsId, customerId) {
	if (sessionStorage.target && sessionStorage.target != "list") {
		$("#editBtn").hide();
	}
	var href = "";
	if (sessionStorage.target == "list") {
		href = ctx + "/base/customer/list";
	}
	if (sessionStorage.target == "customerSearch") {
		href = ctx + "/expert/customerExam/customer";
	}
	if (sessionStorage.target == "customerNotActive") {
		href = ctx + "/expert/customerExam/customerNotActive";
	}
	if (sessionStorage.target == "detail") {
		href = ctx + "/expert/expertManualService/detail?id=" + emsId;
	}
	if (sessionStorage.target == "detailForm") {
		href = ctx + "/expert/expertManualService/form";
	}
	if (sessionStorage.target == "cash") {
		href = ctx + "/cash/member/detail?id=" + customerId;
	}
	$("#returnBtn").attr("href", href);
}

function disableExitMenu() {
	$("#header a").attr("href", "#");
}